<template>
  <div v-permission="['stock:warehouse:query']">
    <page-wrapper content-full-height fixed-height>
      <!-- 表格区域 -->
      <vxe-grid id="InformationStock" ref="grid" resizable show-overflow highlight-hover-row keep-source row-id="id"
        :columns="tableColumn" :toolbar-config="toolBarConfig" :custom-config="{}" :pager-config="{}" :data="tableData"
        :loading="loading">
        <!-- 搜索区域 -->
        <template #form>
          <j-border class="search-wrapper">
            <j-form label-width="80px" class="search-form">
              <div class="form-grid">
                <j-form-item label="单据编号" style="width: 100%">
                  <a-input v-model:value.trim="searchFormData.code" allow-clear placeholder="请输入单据编号" />
                </j-form-item>
                <j-form-item label="发票类型" style="width: 100%">
                  <a-select v-model:value="searchFormData.lei" allow-clear placeholder="请选择发票类型">
                    <a-select-option value="1">普通发票</a-select-option>
                    <a-select-option value="2">专用发票</a-select-option>
                    <a-select-option value="3">农副产品发票</a-select-option>
                    <a-select-option value="4">红字专用发票</a-select-option>
                    <a-select-option value="5">红字普通发票</a-select-option>
                    <a-select-option value="6">红字农副产品发票</a-select-option>
                  </a-select>
                </j-form-item>
                <j-form-item label="供应商" style="width: 100%">
                  <a-select v-model:value="searchFormData.status" allow-clear placeholder="请选择仓库状态">
                    <a-select-option value="1">北梦客户</a-select-option>
                    <a-select-option value="2">测试用户</a-select-option>
                    <a-select-option value="3">软件用户</a-select-option>
                  </a-select>
                </j-form-item>
              </div>
            </j-form>
            <div class="search-btn">
              <a-space>
                <a-button type="primary" :icon="h(SearchOutlined)" @click="search">查询</a-button>
              </a-space>
            </div>
          </j-border>
        </template>
        <!-- 工具栏 -->
        <template #toolbar_buttons>
          <a-space>
            <a-button type="primary" :icon="h(PlusOutlined)" @click="openAddDialog()">新增</a-button>
            <a-button type="primary" danger :icon="h(DeleteOutlined)" @click="onDelete">删除</a-button>
            <a-button :icon="h(DownloadOutlined)" @click="onDown">导出</a-button>
          </a-space>
        </template>

        <!-- 状态列 -->
        <template #status_default="{ row }">
          <a-tag :color="getStatusColor(row.status)">
            {{ getStatusText(row.status) }}
          </a-tag>
        </template>

        <!-- 操作列 -->
        <template #action_default="{ row }">
          <table-action outside :actions="createActions(row)" />
        </template>
      </vxe-grid>

      <!-- 新增/修改窗口 -->
      <managerial-dialog :id="currentId" v-model:visible="dialogVisible" :current-row="currentRow"
        @success="handleSuccess" />
    </page-wrapper>
  </div>
</template>

<script lang="ts">
import { h, defineComponent, ref } from 'vue';
import { SearchOutlined, PlusOutlined, ReloadOutlined, DeleteOutlined, DownloadOutlined } from '@ant-design/icons-vue';
import { message, Modal } from 'ant-design-vue';
import ManagerialDialog from './components/ManagerialDialog.vue';

export default defineComponent({
  name: 'Warehouse',
  components: {
    SearchOutlined,
    PlusOutlined,
    ReloadOutlined,
    DeleteOutlined,
    DownloadOutlined,
    ManagerialDialog,
  },
  setup() {
    const loading = ref(false);
    const grid = ref();
    const id = ref('');
    const addDialog = ref();
    const updateDialog = ref();
    const warehouseDialog = ref();
    const currentId = ref('');
    const currentRow = ref<any>(null);
    const dialogVisible = ref(false);

    const searchFormData = ref({
      code: '',
      lei: undefined,
      status: undefined,
    });

    const tableColumn = [
      { type: 'checkbox' as const, width: 50, fixed: 'left' as const },
      { field: 'code', title: '发票', width: 140 },
      { field: 'name', title: '供应商', minWidth: 140 },
      { field: 'note', title: '采购金额', minWidth: 200 },
      { field: 'status', title: '税率', width: 100, slots: { default: 'status_default' } },
      { field: 'createName', title: '核销金额', width: 140 },
      { field: 'createTime', title: '发票类型', width: 140 },
      { field: 'reviseName', title: '核销状态', width: 140 },
      { field: 'reviseTime', title: '制单人', width: 140 },
      { field: 'notifier', title: '制单时间', width: 140 },
      { field: 'notifier', title: '状态', width: 140 },
      { field: 'action', title: '操作', width: 120, slots: { default: 'action_default' }, fixed: 'right' as const },
    ];

    const toolBarConfig = {
      slots: {
        buttons: 'toolbar_buttons',
      },
    };

    // 模拟表格数据
    const mockData = [
      {
        id: '1',
        code: 'W001',
        name: '测试仓库1',
        status: 'ENABLE',
        note: '测试仓库1备注信息',
        createName: '张三',
        createTime: '2024-01-01 10:00:00',
        reviseName: '李四',
        reviseTime: '2024-01-01 11:00:00',
        notifier: '王五'
      },
      {
        id: '2',
        code: 'W002',
        name: '测试仓库2',
        status: 'DISABLE',
        note: '测试仓库2备注信息',
        createName: '李四',
        createTime: '2024-01-02 10:00:00',
        reviseName: '张三',
        reviseTime: '2024-01-02 11:00:00',
        notifier: '赵六'
      },
      {
        id: '3',
        code: 'W003',
        name: '测试仓库3',
        status: 'ENABLE',
        note: '测试仓库3备注信息',
        createName: '王五',
        createTime: '2024-01-03 10:00:00',
        reviseName: '赵六',
        reviseTime: '2024-01-03 11:00:00',
        notifier: '张三'
      }
    ];

    const tableData = ref(mockData);

    const getStatusColor = (status: string) => {
      return status === 'ENABLE' ? 'success' : 'error';
    };

    const getStatusText = (status: string) => {
      const textMap: Record<string, string> = {
        ENABLE: '启用',
        DISABLE: '禁用'
      };
      return textMap[status] || '未知';
    };

    const search = () => {
      // 实现查询逻辑
      console.log('Searching with:', searchFormData.value);
    };
    const resetSearch = () => {
      searchFormData.value = {
        code: '',
        name: '',
        status: undefined,
      };
      search();
    };
    const openAddDialog = () => {
      currentId.value = '';
      currentRow.value = {
        code: '',
        username: '',
        name: '',
        department: '',
        notifier: '',
      };
      dialogVisible.value = true;
    };

    const openEditDialog = (row: any) => {
      currentId.value = row.id;
      currentRow.value = {
        code: row.code,
        username: row.username,
        name: row.name,
        department: row.department,
        notifier: row.notifier,
      };
      dialogVisible.value = true;
    };

    const handleSuccess = () => {
      dialogVisible.value = false;
      search();
    };

    const createActions = (row: any) => {
      return [
        {
          label: '编辑',
          onClick: () => openEditDialog(row),
        }
      ];
    };

    // 处理删除
    const onDelete = async () => {
      const selections = grid.value?.getCheckboxRecords();
      if (!selections || selections.length === 0) {
        message.warning('请选择要删除的数据');
        return;
      }

      Modal.confirm({
        title: '确认删除',
        content: '确定要删除选中的数据吗？',
        okText: '确定',
        cancelText: '取消',
        onOk: async () => {
          try {
            // 调用删除API
            // await api.batchDelete(selections.map(item => item.id));
            message.success('删除成功');
            search();
          } catch (error) {
            console.error('删除失败:', error);
            message.error('删除失败');
          }
        }
      });
    };

    // 处理导出
    const onDown = () => {
      const selections = grid.value?.getCheckboxRecords();
      if (!selections || selections.length === 0) {
        message.warning('请选择要导出的数据');
        return;
      }

      try {
        // 构建导出数据
        const exportData = selections.map(item => ({
          code: item.code,
          name: item.name,
          status: getStatusText(item.status),
          note: item.note,
          createName: item.createName,
          createTime: item.createTime,
          reviseName: item.reviseName,
          reviseTime: item.reviseTime,
          notifier: item.notifier
        }));

        // 创建CSV内容
        const headers = ['编号', '名称', '状态', '备注', '创建人', '创建时间', '修改人', '修改时间', '通知人'];
        const csvContent = [
          headers.join(','),
          ...exportData.map(row => Object.values(row).join(','))
        ].join('\n');

        // 创建下载链接
        const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = `发票管理_${new Date().toISOString().split('T')[0]}.csv`;
        link.click();

        message.success('导出成功');
      } catch (error) {
        console.error('导出失败:', error);
        message.error('导出失败');
      }
    };

    return {
      h,
      loading,
      grid,
      id,
      addDialog,
      updateDialog,
      searchFormData,
      SearchOutlined,
      DeleteOutlined,
      DownloadOutlined,
      PlusOutlined,
      tableColumn,
      toolBarConfig,
      tableData,
      search,
      resetSearch,
      openAddDialog,
      createActions,
      getStatusColor,
      getStatusText,
      ManagerialDialog,
      currentId,
      currentRow,
      dialogVisible,
      openEditDialog,
      handleSuccess,
      onDelete,
      onDown,
    };
  },
});
</script>

<style lang="less" scoped>
.search-wrapper {
  position: relative;
  background-color: #fff;
  padding: 16px;
  border-radius: 2px;
  display: flex;

  :deep(.search-form) {
    width: 60%;
    // margin-right: 100px;

    .form-grid {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 20px;
    }

    .ant-form-item {
      margin: 0;
    }

    .ant-input,
    .ant-select {
      width: 100%;
    }
  }

  :deep(.j-form-item-container) {
    display: flex;
    flex-direction: column;
    align-items: stretch;

    .ant-input-wrapper {
      width: 100%;
    }
  }

  .search-btn {
    display: flex;
    justify-content: center;
  }
}

.vxe-grid {
  margin-bottom: 16px;
}
</style>
